

import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

public class Client extends Thread {
	private HashMap<String, Node> nodes;
	private HashMap<String, Boolean> connected;
	private HashMap<String, Sender> senders;

	public Client(HashMap<String, Node> nodes, HashMap<String, Sender> senders) {
		this.nodes = nodes;
		this.senders = senders;
		connected = new HashMap<String, Boolean>();
		for (Iterator<Entry<String, Node>> it = nodes.entrySet().iterator(); it
				.hasNext();) {
			connected.put(it.next().getKey(), false);
		}
	}

	public void run() {
		int n = 0;
		while (true) {
			for (Iterator<Entry<String, Boolean>> it = connected.entrySet()
					.iterator(); it.hasNext();) {
				try {
					sleep(100);
					Entry<String, Boolean> e = it.next();
					if (!e.getValue()) {
						Node node = nodes.get(e.getKey());

						Socket s = new Socket(node.getIp(), node.getPort());
						if (s.isConnected()) {
							Sender sender = new Sender(s);

							senders.put(node.getName(), sender);
							connected.put(node.getName(), true);
							n++;
						}
					}
				} catch (Exception e) {
					// e.printStackTrace();
				}

			}

			if (n == nodes.size())
				break;

		}
		System.out.println("client out of loop");
	}
}
